package com.dhcc.DRGsHosp.facade.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Named;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.QueryChannelService;
import org.dayatang.utils.Page;
import org.openkoala.koala.commons.InvokeResult;
import org.springframework.beans.factory.annotation.Autowired;

import com.dhcc.DRGsHosp.application.DepGroupApplication;
import com.dhcc.DRGsHosp.application.DepartmentApplication;
import com.dhcc.DRGsHosp.core.domain.DepGroup;
import com.dhcc.DRGsHosp.facade.DepGroupFacade;
import com.dhcc.DRGsHosp.facade.dto.DepGroupDTO;
import com.dhcc.DRGsHosp.facade.impl.assembler.DepGroupAssembler;
import com.dhcc.DRGsHosp.infra.util.ExcelUtil;

@Named("drgsHospFacadeImpl8")
public class DepGroupFacadeImpl implements DepGroupFacade {

	@Autowired
	private DepGroupApplication  application;

	@Autowired
	private DepartmentApplication  departmentApplication;
	
	private QueryChannelService queryChannel;

    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
	
	public InvokeResult getDepGroup(String depGroupCode) {
		String depNames=departmentApplication.findDepNamesByDepGroupCode(depGroupCode);
		return InvokeResult.success(depNames);
		//return InvokeResult.success(DepGroupAssembler.toDTO(application.getDepGroup(depGroupCode)));
	}
	
	public InvokeResult creatDepGroup(DepGroupDTO depGroupDTO) {
		DepGroup dgp = application.getDepGroup(depGroupDTO.getDepGroupCode());
		if(null == dgp){
			application.creatDepGroup(DepGroupAssembler.toEntity(depGroupDTO));
			return InvokeResult.success();
		}else{
			return InvokeResult.failure("此专业组编码已存在！");
		}
		
	}
	
	public InvokeResult updateDepGroup(DepGroupDTO depGroupDTO) {
		application.updateDepGroup(DepGroupAssembler.toEntity(depGroupDTO));
		return InvokeResult.success();
	}
	
	public InvokeResult removeDepGroup(String depGroupCode) {
		application.removeDepGroup(application.getDepGroup(depGroupCode));
		return InvokeResult.success();
	}
	
	public InvokeResult removeDepGroups(String[] depGroupCodes) {
		Set<DepGroup> depGroups= new HashSet<DepGroup>();
		Map<String, Object> depGroupInfo = new HashMap<String, Object>();
		for ( String depGroupCode : depGroupCodes) {
			DepGroup depGroup = application.getDepGroup(depGroupCode);
			String depGroupName = depGroup.getDepGroupDesc();
			depGroups.add(depGroup);
			//查找当前科室组下的科室
			String depNames=departmentApplication.findDepNamesByDepGroupCode(depGroupCode);
			if(!"".equals(depNames))
			{
				depGroupInfo.put(depGroupName, depNames);
			}
		}
		if(!depGroupInfo.isEmpty())
		{
			return InvokeResult.failure("请删除专业组所辖的科室");
		}
		application.removeDepGroups(depGroups);
		return InvokeResult.success();
	}
	
	public List<DepGroupDTO> findAllDepGroup() {
		return DepGroupAssembler.toDTOs(application.findAllDepGroup());
	}
	
	public Page<DepGroupDTO> pageQueryDepGroup(DepGroupDTO queryVo, int currentPage, int pageSize) {
		List<Object> conditionVals = new ArrayList<Object>();
	   	StringBuilder jpql = new StringBuilder("select _depGroup from DepGroup _depGroup   where 1=1 ");
	   	if (queryVo.getDepGroupCode() != null && !"".equals(queryVo.getDepGroupCode())) {
	   		jpql.append(" and _depGroup.depGroupCode like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepGroupCode()));
	   	}		
	   	if (queryVo.getDepGroupDesc() != null && !"".equals(queryVo.getDepGroupDesc())) {
	   		jpql.append(" and _depGroup.depGroupDesc like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepGroupDesc()));
	   	}		
	   	if (queryVo.getDepgroupLeader() != null && !"".equals(queryVo.getDepgroupLeader())) {
	   		jpql.append(" and _depGroup.depgroupLeader like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepgroupLeader()));
	   	}		
	   	if (queryVo.getDepGroupPhone() != null && !"".equals(queryVo.getDepGroupPhone())) {
	   		jpql.append(" and _depGroup.depGroupPhone like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepGroupPhone()));
	   	}		
	   	if (queryVo.getDepGroupOrder() != null && !"".equals(queryVo.getDepGroupOrder())) {
	   		jpql.append(" and _depGroup.depGroupOrder like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepGroupOrder()));
	   	}	
	   	jpql.append(" order by to_number(_depGroup.depGroupOrder)");
        Page<DepGroup> pages = getQueryChannelService()
		   .createJpqlQuery(jpql.toString())
		   .setParameters(conditionVals)
		   .setPage(currentPage, pageSize)
		   .pagedList();
		   
        return new Page<DepGroupDTO>(pages.getStart(), pages.getResultCount(),pageSize, DepGroupAssembler.toDTOs(pages.getData()));
	}
	
	/**
	 * 
	 */
	@Override
	public Boolean isOrderExist(String order,String code){
		return application.isOrderExist(order,code);
	}

	@Override
	public InvokeResult depGroupImport(String filePath) {
		// 查询最大显示序号
		Double order = application.findOrderMax() ;
		StringBuffer message = new StringBuffer();//返回前台的信息
		String extension = filePath.substring(filePath.lastIndexOf("."));// 扩展名
		Workbook workbook = null;
		Sheet sheet = null;
		if (extension.equals(".xls")) {
			try {
				workbook = new HSSFWorkbook(new FileInputStream(
						filePath));
				sheet = (HSSFSheet) workbook.getSheetAt(0);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else if (extension.equals(".xlsx")) {
			try {
				workbook = new XSSFWorkbook(new FileInputStream(
						filePath));
				sheet = (XSSFSheet) workbook.getSheetAt(0);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.err.println("上传的文件不是有效的excel文件！");
		}
		int rowNum=sheet.getLastRowNum();//行数
		int errorRow = 0;
		Row row = null ;
		// 存放文件的表头位置
		Map<String,Object> titlemap = new HashMap<>();
		// 标题行
		Row headrow = sheet.getRow(0);
		int headCount = headrow.getLastCellNum();
		Cell cell=null;
		for (int i = 0; i < headCount; i++) {
			cell = headrow.getCell((short) i);
			titlemap.put(cell.getStringCellValue(), i);
		}
		int rowCnt=0;
		try {
			message.setLength(0);
			for(int i = 1 ; i <= rowNum ; i++) {
				errorRow = i;
				row=sheet.getRow(i);
				// 该行为空时解析下一行
				if(null == row) {
					continue ;
				}
				DepGroup depGroup=new DepGroup();
				cell = row.getCell((int) (titlemap.get("代码") != null ? titlemap.get("代码"):1000));
				String depGroupCode=ExcelUtil.getCellValue(cell);
				if( null == depGroupCode) {
					message.append("第" + (i) +"行数据没有科室组代码，请检查。<br>"); 
					continue ;
				}
				depGroup.setDepGroupCode(depGroupCode);
				cell = row.getCell((int) (titlemap.get("名称") != null ? titlemap.get("名称"):1000));
				String depGroupDesc=ExcelUtil.getCellValue(cell);
				if( null == depGroupDesc) {
					message.append("第" + (i) +"行数据没有科室组名称，请检查。<br>"); 
					continue ;
				}
				depGroup.setDepGroupDesc(depGroupDesc);
				cell = row.getCell((int) (titlemap.get("负责人") != null ? titlemap.get("负责人"):1000));
				depGroup.setDepgroupLeader(ExcelUtil.getCellValue(cell));
				cell = row.getCell((int) (titlemap.get("电话") != null ? titlemap.get("电话"):1000));
				depGroup.setDepGroupPhone(ExcelUtil.getCellValue(cell));
				cell = row.getCell((int) (titlemap.get("顺序") != null ? titlemap.get("顺序"):1000));
				String depGroupOrder=ExcelUtil.getCellValue(cell);
				if(depGroupOrder == null){
					depGroup.setDepGroupOrder(++order);
				} else if(depGroupOrder!=null&&!depGroupOrder.matches("^\\d+$")) {
					message.append("第"+(i)+"行 数据顺序不是合法数字，请检查。 </br>");
					continue ;
				}
				else if(depGroupOrder!=null&&application.isOrderExist(depGroupOrder, depGroupCode)){
					message.append("第" + (i) +"行数据顺序已经存在。<br>"); 
					continue ;
				}
				else{
					double orderTemp = depGroupOrder==null?null:Double.valueOf(depGroupOrder);
					if(order<orderTemp) {
						order = orderTemp;
					}
					depGroup.setDepGroupOrder(orderTemp);
				}
				application.creatDepGroup(depGroup);
				rowCnt++;
			}
			message.append("成功导入"+rowCnt+"条数据!<br>");
		} catch (Exception e) {
			e.printStackTrace();
			message.append("第" + (errorRow) +"行数据导入时报错，导入终止。<br>"); 
			return InvokeResult.failure(message.toString());
		} finally {
			ExcelUtil.deleteFile(filePath) ;
		}
		return InvokeResult.success(message) ;
	}
}
